﻿using community.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace community.Controllers
{
    [Route("api/residents")]
    [ApiController]
    public class ResidentsController : ControllerBase
    {
        private static List<Resident> residents = new List<Resident>();

        // 录入居民信息
        [HttpPost]
        public IActionResult CreateResident([FromBody] Resident resident)
        {
            resident.Id = residents.Count + 1;
            resident.CreatedAt = DateTime.UtcNow;
            resident.UpdatedAt = DateTime.UtcNow;
            residents.Add(resident);
            return CreatedAtAction(nameof(GetResidentById), new { id = resident.Id }, resident);
        }

        // 查询所有居民信息
        [HttpGet]
        public IActionResult GetAllResidents()
        {
            return Ok(residents);
        }

        // 根据ID查询居民信息
        [HttpGet("{id}")]
        public IActionResult GetResidentById(int id)
        {
            var resident = residents.Find(r => r.Id == id);
            if (resident == null)
            {
                return NotFound();
            }
            return Ok(resident);
        }

        // 修改居民信息
        [HttpPut("{id}")]
        public IActionResult UpdateResident(int id, [FromBody] Resident updatedResident)
        {
            var resident = residents.Find(r => r.Id == id);
            if (resident == null)
            {
                return NotFound();
            }

            resident.Name = updatedResident.Name;
            resident.Phone = updatedResident.Phone;
            resident.IdCard = updatedResident.IdCard;
            resident.Gender = updatedResident.Gender;
            resident.BirthDate = updatedResident.BirthDate;
            resident.Address = updatedResident.Address;
            resident.HouseId = updatedResident.HouseId;
            resident.UpdatedAt = DateTime.UtcNow;

            return NoContent();
        }

        // 删除居民信息
        [HttpDelete("{id}")]
        public IActionResult DeleteResident(int id)
        {
            var resident = residents.Find(r => r.Id == id);
            if (resident == null)
            {
                return NotFound();
            }

            residents.Remove(resident);
            return NoContent();
        }
    }
}
